import sys
from time import sleep

import pygame
from bullet import Bullet
from alien import Alien


def fire_bullet(ai_settings, screen, ship, bullets):
    if len(bullets) < ai_settings.bullet_allowed:
        new_bullet = Bullet(ai_settings, screen, ship)
        bullets.add(new_bullet)


def check_keydown_events(event, ai_settings, screen, stats, ship, aliens, bullets):
    if event.key == pygame.K_RIGHT:
        ship.moving_right = True
    elif event.key == pygame.K_LEFT:
        ship.moving_left = True
    elif event.key == pygame.K_SPACE:
        fire_bullet(ai_settings, screen, ship, bullets)
    elif event.key == pygame.K_q:
        sys.exit()
    elif event.key == pygame.K_RETURN:
        start_game(ai_settings, screen, stats, ship, aliens, bullets)


def check_keyup_events(event, ship):
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    elif event.key == pygame.K_LEFT:
        ship.moving_left = False


def check_events(ai_settings, screen, stats, play_button, ship, aliens, bullets):
    """响应按键和鼠标事件"""
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            check_keydown_events(event, ai_settings, screen, stats, ship, aliens, bullets)
        elif event.type == pygame.KEYUP:
            check_keyup_events(event, ship)
        elif event.type == pygame.MOUSEBUTTONDOWN:
            mousex, mousey = pygame.mouse.get_pos()
            check_play_button(ai_settings, screen, stats, play_button, ship, aliens, bullets, mousex, mousey)


def check_play_button(ai_settings, screen, stats, play_button, ship, aliens, bullets, mousex, mousey):
    if play_button.rect.collidepoint(mousex, mousey):
        start_game(ai_settings, screen, stats, ship, aliens, bullets)


def start_game(ai_settings, screen, stats, ship, aliens, bullets):
    if not stats.game_active:
        # 隐藏鼠标光标
        pygame.mouse.set_visible(False)
        # 重置子弹，飞船，外星人速度
        ai_settings.initialize_dynamic_settings()
        # 重置游戏统计信息
        stats.ships_left = ai_settings.ship_limit
        stats.game_active = True

        # 情况外星人和子弹
        aliens.empty()
        bullets.empty()

        # 创建一群新的外星人，并让飞船居中
        create_fleet(ai_settings, screen, aliens, ship)
        ship.center_ship()


def update_screen(ai_settings, stats, scoreboard, screen, ship, aliens, bullets, play_button):
    """ 更新屏幕上的图像，并切换到新屏幕 """
    # 每次循环时都重绘屏幕
    screen.fill(ai_settings.bg_color)
    for bullet in bullets:
        bullet.draw_bullet()
    ship.blitme()
    aliens.draw(screen)
    scoreboard.show_score()
    if not stats.game_active:
        play_button.draw_button()
    # 让最近绘制的屏幕可见
    pygame.display.flip()


def update_bullets(ai_settings, screen, ship, bullets, aliens):
    """
    在更新子弹位置的时候，增加判断是否和外星人发生碰撞，如果发生碰撞就让子弹和外星人消失，
    这个功能借助pygame.sprite.groupcollide()方法，这个方法传入两个group和两个布尔参数
    这个方法返回值是一个字典，key为重合的元素第一个group的元素，value为第二个group的元素
    两个布尔参数，分别对应是否删除传入的两个group的重合的元素
    """
    bullets.update()
    for bullet in bullets.copy():
        if bullet.rect.y <= 0:
            bullets.remove(bullet)

    # 将判断碰撞及碰撞后的处理提取为一个函数
    check_bullet_alien_collisions(ai_settings, screen, ship, bullets, aliens)


def check_bullet_alien_collisions(ai_settings, screen, ship, bullets, aliens):
    # 判断碰撞
    collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)

    # 坚持外星人是否被全部消灭，如果全部消灭，生成新的外星人群
    if len(aliens) == 0:
        bullets.empty()
        ai_settings.increase_speed()
        create_fleet(ai_settings, screen, aliens, ship)


def check_fleet_edges(ai_settings, aliens):
    for alien in aliens:
        if alien.check_edges():
            change_fleet_direction(ai_settings, aliens)
            break


def change_fleet_direction(ai_settings, aliens):
    """向下移动，并改变移动方向"""
    for alien in aliens:
        alien.y += ai_settings.fleet_drop_speed
        alien.rect.y = alien.y

    ai_settings.fleet_direction *= -1


def update_aliens(ai_settings, stats, screen, ship, aliens, bullets):
    check_fleet_edges(ai_settings, aliens)
    aliens.update()

    # 在更新完外星人位置后，要判断是否与飞船发生碰撞，借助pygame.sprite.spritecollideany()方法
    # 这个方法传入一个精灵和一个group，判断group中是否有元素与精灵（单个元素）碰撞，返回碰撞的第一个元素，否则返回None
    if pygame.sprite.spritecollideany(ship, aliens):
        ship_hit(ai_settings, stats, screen, ship, aliens, bullets)

    check_aliens_bottom(ai_settings, stats, screen, ship, aliens, bullets)


def check_aliens_bottom(ai_settings, stats, screen, ship, aliens, bullets):
    """检查飞船是否到达屏幕底部"""
    screen_rect = screen.get_rect()
    for alien in aliens:
        if alien.rect.bottom >= screen_rect.bottom:
            ship_hit(ai_settings, stats, screen, ship, aliens, bullets)
            break


def ship_hit(ai_settings, stats, screen, ship, aliens, bullets):
    # 如果飞船数量大于0才能继续游戏
    if stats.ships_left > 0:
        # 设置飞船数量-1
        stats.ships_left -= 1

        # 清空现有子弹和外星人
        bullets.empty()
        aliens.empty()

        # 创建新的外星人群
        create_fleet(ai_settings, screen, aliens, ship)
        # 把飞船居中
        ship.center_ship()

        # 暂停1秒
        sleep(1)
    else:
        stats.game_active = False
        # 设置鼠标光标可见
        pygame.mouse.set_visible(True)


def get_number_aliens_x(ai_settings, alien_width):
    # 屏幕左右留出一个外星人宽度，右边会由于外星人中间的空间而多空，这样可以方便移动
    available_space_x = ai_settings.screen_width - 2 * alien_width
    # 我们让每个外星人之间空出一个外星人宽度，这样每个外星人就占2个宽度
    # int()会直接把小数点去掉，不会四舍五入，这样正好，外星人的数量不会多，少一点没关系，多了就会超出屏幕
    number_aliens_x = int(available_space_x / (2 * alien_width))
    return number_aliens_x


def get_number_aliens_y(ai_settings, ship_height, alien_height):
    available_space_y = ai_settings.screen_height - 3 * alien_height - ship_height
    number_aliens_y = int(available_space_y / (2 * alien_height))
    return number_aliens_y


def create_alien(ai_settings, screen, aliens, alien_number, alien_row):
    alien = Alien(ai_settings, screen)
    alien_width = alien.rect.width
    alien_height = alien.rect.height
    alien.x = alien_width + 2 * alien_width * alien_number
    alien.rect.x = alien.x
    alien.y = alien_height + 2 * alien_height * alien_row
    alien.rect.y = alien.y
    aliens.add(alien)


def create_fleet(ai_settings, screen, aliens, ship):
    """创建外星人群，
    1、创建一个外星人
    2、根据外星人的宽度计算一行可以放多少
    3、生成群"""
    alien = Alien(ai_settings, screen)
    number_aliens_x = get_number_aliens_x(ai_settings, alien.rect.width)
    number_aliens_y = get_number_aliens_y(ai_settings, ship.rect.width, alien.rect.width)

    # 创建外星人
    for alien_row in range(number_aliens_y):
        for alien_number in range(number_aliens_x):
            create_alien(ai_settings, screen, aliens, alien_number, alien_row)
